package com.itheima.imclient100.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fullcircle on 2017/7/3.
 */

public class DBUtils {
    private static Context context = null;

    public static void initDBUtils(Context appContext){
        context = appContext;
    }

    public static List<String> initContacts(String username){
        if(context == null){
            throw new IllegalArgumentException("请在application 的oncreate方法中先调用 initDBUtils方法");
        }
        MyOpenHelper openHelper = new MyOpenHelper(context);
        SQLiteDatabase database = openHelper.getReadableDatabase();
//        "select contact from contact_info where username = "+username
        Cursor cursor = database.query("contact_info", new String[]{"contact"}, "username = ?", new String[]{username}, null, null, null);
        List<String> contacts = new ArrayList<>();
        if(cursor !=null){
            while(cursor.moveToNext()){
                contacts.add(cursor.getString(0));
            }
        }
        cursor.close();
        database.close();
        return contacts;
    }

    public static void updateContacts(String username,List<String> contacts){
        if(context == null){
            throw new IllegalArgumentException("请在application 的oncreate方法中先调用 initDBUtils方法");
        }
        MyOpenHelper openHelper = new MyOpenHelper(context);

        SQLiteDatabase database = openHelper.getReadableDatabase();
        database.beginTransaction();
        try {
            //删除所有的联系人
            //遍历集合 把集合中的联系人重新插入到表中
            database.delete("contact_info","username = ?",new String[]{username});
            if(contacts!=null){
                //准备一个ContentValues 对象
                ContentValues values = new ContentValues();
                //要插入到表中的所有数据 username这一列值都相同 ,所以一提前准备好
                values.put("username",username);
                for(int i=0;i<contacts.size();i++){
                    //向values中 放入联系人的数据
                    values.put("contact",contacts.get(i));
                    //遍历一个联系人之后 向表中插入一条数据
                    database.insert("contact_info",null,values);
                }
            }
            database.setTransactionSuccessful();
        } finally {
            database.endTransaction();
        }
       database.close();

    }
}
